package com.lsx143.wordcount.day10;

import com.lsx143.wordcount.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.*;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Rowtime;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

public class Flink_GroupWindow {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        DataStream<WaterSensor> waterSensorStream =
                env
                        .fromElements(new WaterSensor("sensor_1", 1001L, 10),
                                new WaterSensor("sensor_1", 7000L, 20),
                                new WaterSensor("sensor_1", 4001L, 40),
                                new WaterSensor("sensor_1", 5000L, 50),
                                new WaterSensor("sensor_2", 3000L, 30),
                                new WaterSensor("sensor_2", 6000L, 60))
                        .assignTimestampsAndWatermarks(
                                WatermarkStrategy
                                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                        .withTimestampAssigner((ws, ts) -> ws.getTs())
                        );

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        // 每隔5s统计最近5s内每个传感器的水位和
        Table table = tEnv.fromDataStream(waterSensorStream, $("id"), $("ts").rowtime(), $("vc"));

        // 创建一个滚动窗口
//        GroupWindow w = Tumble.over(Expressions.lit(5).second()).on($("ts")).as("w");
//        GroupWindow w = Slide.over(lit(5).second()).every(lit(2).second()).on($("ts")).as("w");
        GroupWindow w = Session.withGap(lit(2).second()).on($("ts")).as("w");
        table
                .window(w)
                .groupBy($("id"), $("w"))
                .select($("id"), $("w").start().as("stt"), $("w").end().as("edt"), $("vc").sum().as("vc_sum"))
                .execute()
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}